/*
 * tp boole
 */
package boole.utils.provider;

import boole.circuit.Composite;
import boole.circuit._Composant;
import boole.utils.BadIONumberException;
import boole.utils.ComposantInstantiationException;
import boole.utils.ComposantNotFoundException;
import java.util.HashMap;

/**
 *
 * @author Rémi PIOTAIX <remi.piotaix@gmail.com>
 */
public abstract class AbstractComposantProvider implements ComposantProviderInterface {

    private HashMap<String, Class<? extends _Composant>> composants = new HashMap();

    public AbstractComposantProvider() {
        init();
    }

    @Override
    public boolean contains(String nom) {
        return composants.containsKey(nom);
    }

    @Override
    public boolean contains(Class<? extends _Composant> composantClass) {
        return composants.containsValue(composantClass);
    }

    @Override
    public void registerComposant(String nom, Class<? extends _Composant> classe) {
        if (!composants.containsKey(nom)) {
            composants.put(nom, classe);
        }
    }
    
    @Override
    public _Composant newInstance(String nom, int nombreEntrees, int nombreSorties) {
        Class<? extends _Composant> c = composants.get(nom);
        if (c == null) {
            throw new ComposantNotFoundException(nom);
        }

        try {
            _Composant composant = c.newInstance();
            if (composant.getNombreEntrees() == nombreEntrees && composant.getNombreSorties() == nombreSorties) {
                return composant;
            } else {
                throw new BadIONumberException(nom, composant, nombreEntrees, nombreSorties);
            }
        } catch (InstantiationException | IllegalAccessException ex) {
            throw new ComposantInstantiationException(nom);
        }

    }

    protected abstract void init();
}
